import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:xvideos/assets_tool/app_colors.dart';
import 'package:xvideos/hj_utils/api_service/ai_service.dart';
import 'package:xvideos/routers/jump_router.dart';
import 'package:xvideos/tools_base/debug_log.dart';
import 'package:xvideos/tools_base/loading/loading_alert_widget.dart';

import '../../../../hj_utils/global.dart';
import '../../../../hj_utils/widget_utils.dart';
import '../../mine_utils.dart';
import '../mode/ai_gril_resp.dart';

//ai女友弹窗
class AIGrilfriendSheet extends StatefulWidget {
  final List<AIGirlFriendCurrency>? list;
  const AIGrilfriendSheet({super.key, this.list});

  @override
  State<AIGrilfriendSheet> createState() => _AIGrilfriendSheetState();
}

class _AIGrilfriendSheetState extends State<AIGrilfriendSheet> {
  int selectIndex = 0;

  @override
  Widget build(BuildContext context) {
    return Material(
      color: Colors.transparent,
      child: Container(
        decoration: const BoxDecoration(
          color: Color(0xff1D2236),
          borderRadius: BorderRadius.only(
            topLeft: Radius.circular(18),
            topRight: Radius.circular(18),
          ),
        ),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const SizedBox(height: 18),
            Container(
              height: 5,
              width: 36,
              decoration: BoxDecoration(
                borderRadius: BorderRadius.circular(2.5),
                color: Colors.white.withOpacity(.1),
              ),
            ),
            Padding(
              padding: const EdgeInsets.only(top: 18, bottom: 12),
              child: Text(
                'AI女友',
                style: textStyle(20, Colors.white, FontWeight.w600),
              ),
            ),
            Text(
              '充值积分',
              style: textStyle(14, Colors.white.withOpacity(.8), FontWeight.w400),
            ),
            GridView.builder(
              padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 18),
              shrinkWrap: true,
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 3,
                childAspectRatio: 106 / 60,
                crossAxisSpacing: 12,
                mainAxisSpacing: 12,
              ),
              itemCount: widget.list?.length ?? 0,
              itemBuilder: (context, index) => _buildItem(index),
            ),
            Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Row(
                  children: [
                    const SizedBox(width: 28),
                    Text(
                      '支付小贴士：',
                      style: textStyle(14, Colors.white, FontWeight.w500),
                      textAlign: TextAlign.left,
                    ),
                  ],
                ),
                const SizedBox(height: 6),
                Row(
                  children: [
                    const SizedBox(width: 28),
                    Expanded(
                      child: Text(
                        '1.因超时支付无法到账，请重新发起。\n2.连续发起且未支付，账号可能被加入黑名单\n3.充值成功后会在1～5分钟内到账，可重新刷新进入当前页面',
                        style: textStyle(12, Colors.white.withOpacity(.6), FontWeight.w400),
                      ),
                    ),
                    const SizedBox(width: 28),
                  ],
                )
              ],
            ),
            const SizedBox(height: 18),
            GestureDetector(
              onTap: () => _onPayAction(),
              child: Container(
                margin: const EdgeInsets.symmetric(horizontal: 16),
                height: 44,
                alignment: Alignment.center,
                decoration: BoxDecoration(
                  gradient: const LinearGradient(
                    colors: [
                      Color(0xff1E3C72),
                      Color(0xff5F40B6),
                      Color(0xff1E3C72),
                      Color(0xff2A5298),
                    ],
                    begin: Alignment.centerLeft,
                    end: Alignment.centerRight,
                  ),
                  borderRadius: BorderRadius.circular(22),
                ),
                child: Text(
                  '${(widget.list?[selectIndex].price ?? 0).truncate()}/立即支付',
                  style: textStyle(16, Colors.white, FontWeight.w400),
                ),
              ),
            ),
            const SizedBox(height: 18),
            buildRichText(),
            const SizedBox(height: 30),
          ],
        ),
      ),
    );
  }

  _buildItem(int index) {
    AIGirlFriendCurrency? item = widget.list?[index];
    bool isSelected = selectIndex == index;
    return GestureDetector(
      onTap: () {
        selectIndex = index;
        setState(() {});
      },
      child: Container(
        decoration: BoxDecoration(
          color: isSelected ? const Color(0xff4039A1) : Colors.white.withOpacity(.05),
          borderRadius: BorderRadius.circular(6),
          border: Border.all(
            color: isSelected ? Color(0xff30509C) : Colors.white.withOpacity(.1),
          ),
        ),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              '${(item?.coins ?? 0)}积分',
              style: textStyle(16, isSelected ? Color(0xffAFABFF) : Color(0xff7D95D5), FontWeight.w400),
            ),
            const SizedBox(height: 4),
            Text(
              '${(item?.price ?? 0).truncate()}金币', //
              style: textStyle(12, isSelected ? Color(0x4DF3F5FF) : Colors.white.withOpacity(.3), FontWeight.w400),
            ),
          ],
        ),
      ),
    );
  }

  ///构建富文本
  RichText buildRichText() {
    return RichText(
      //文字居中
      textAlign: TextAlign.center,
      //文字区域
      text: TextSpan(
        text: '支付中如有问题 请联系在线客服',
        style: textStyle(12, Colors.white.withOpacity(.6), FontWeight.w400),
        children: [
          TextSpan(
            text: '在线客服',
            style: TextStyle(color: AppColors.primaryHighColor),
            //点击事件
            recognizer: TapGestureRecognizer()
              ..onTap = () {
                MineUtils.goCSPage();
              },
          ),
        ],
      ),
    );
  }

  _onPayAction() async {
    AIGirlFriendCurrency? item = widget.list?[selectIndex];
    Map<String, dynamic> data = {'id': item?.id ?? ''};
    try {
      LoadingAlertWidget.show(Get.context!);
      final value = await AIService.exchangeAiFriend(data);
      LoadingAlertWidget.cancel(Get.context!);
      if (value is String) {
        showToast(value);
      } else {
        if (value.code == 200) {
          showToast('充值成功');
          Get.back();
        } else if (value.code == 8000) {
          //金豆不足
          showToast('金币不足，请充值');
          jumpToWalletPage(tabPosition: 1);
        }
      }
    } catch (e) {
      LoadingAlertWidget.cancel(Get.context!);
      debugLog(e);
    }
  }
}
